<?php

namespace App\Http\Controllers;

use App\Imports\DormMeterImport;
use App\Models\Building;
use App\Models\Dorm;
use App\Models\DormMeter;
use App\Models\DormMeterRecord;
use App\Models\DormType;
use App\Models\MeterType;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\DormMeterCreateRequest;
use App\Http\Requests\DormMeterUpdateRequest;
use App\Models\DormMeterAdjust;
use App\Repositories\DormMeterRepository;

/**
 * Class DormMetersController.
 *
 * @package namespace App\Http\Controllers;
 */
class DormMetersController extends Controller
{
    /**
     * @var DormMeterRepository
     */
    protected $repository;

    /**
     * DormMetersController constructor.
     *
     * @param DormMeterRepository $repository
     * @param DormMeterValidator $validator
     */
    public function __construct(DormMeterRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        if (\Route::currentRouteName() == 'api.dorm-meters.index') {
            $dormMeters = $this->repository->findWhere(['active' => 1], ['dorm_id', 'meter_type_id', 'last_reading']);
        } else {
            if (\request()->get('export') == 2) {
                $dormMeters = $this->repository->with(['dorm', 'meter_type'])->all();
            } else {
                $dormMeters = $this->repository->with(['company', 'dorm', 'meter_type'])->paginate(\request()->get('limit', 20));
                \request()->flash();
            }
        }

        if (request()->wantsJson()) {
            return response()->json([
                'data' => $dormMeters,
            ]);
        }
        $buildings = Building::all()->pluck('name', 'id');
        $dormTypes = DormType::all()->pluck('name', 'id');

        return view('dormMeters.index', compact('dormMeters', 'buildings', 'dormTypes'));
    }

    public function create()
    {
        $dorms = Dorm::shouldInstallMeter()->pluck('code', 'id');
        $meterTypes = MeterType::all();
        return view('dormMeters.create', compact('dorms', 'meterTypes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  DormMeterCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function store(DormMeterCreateRequest $request)
    {
        try {
            $finds = $this->repository->findWhere($request->only(['dorm_id', 'meter_type_id']));
            if ($finds->contains('active', 1)) {
                $msg = "该宿舍已经存在对应的已启用的水电表，不能重复创建！";
                if ($request->wantsJson()) {
                    return response()->json([
                        'error'   => true,
                        'message' => $msg
                    ]);
                }

                return redirect()->back()->withErrors($msg)->withInput();
            }
            $request = $request->merge(['install_date' => $request->get('last_reading_date')]);
            $dormMeter = $this->repository->create($request->all());

            $response = [
                'message' => 'DormMeter created.',
                'data'    => $dormMeter->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessage()
                ]);
            }
            \Log::error($e->getMessage());

            return redirect()->back()->withErrors($e->getMessage())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $dormMeter = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $dormMeter,
            ]);
        }

        return view('dormMeters.show', compact('dormMeter'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $dormMeter = $this->repository->find($id);
        $meterTypes = MeterType::all();
        return view('dormMeters.edit', compact('dormMeter', 'meterTypes'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  DormMeterUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update(DormMeterUpdateRequest $request, $id)
    {
        try {
            //$this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);
            if ($request->get('active') == 0 && $request->get('adjust_date') != null) {
                //停用且调整日期不为空，则将停用日期设为调整日期
                $request = $request->merge(['expire_date' => $request->get('adjust_date')]);
            }
            $dormMeter = $this->repository->update($request->all(), $id);
            $response = [
                'message' => 'DormMeter updated.',
                'data'    => $dormMeter->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $mt = $this->repository->find($id);
        if ($mt->active) {
            $adjust = DormMeterAdjust::query()->where('dorm_meter_id_new', $mt->id)->first();
            if ($adjust) {
                $this->repository->find($adjust->dorm_meter_id_old)->update(['active' => 1]);
                $adjust->delete();
            }
        }
        $deleted = $this->repository->delete($id);

        if (request()->wantsJson()) {

            return response()->json([
                'message' => 'DormMeter deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'DormMeter deleted.');
    }

    public function handleExcelImport(Request $request)
    {
        $file = $request->file('file');
        //判断文件是否上传成功
        if ($file->isValid()) {
            try {
                $import = new DormMeterImport();
                Excel::import($import, $request->file('file'));
                return \response()->json(['code' => 0, 'msg' => "共 $import->total 条，成功 $import->success 条，失败 $import->fail 条，忽略 $import->ignore 条"]);
            } catch (\Exception $exception) {
                return \response()->json(['code' => -1, 'msg' => 'fail:' . $exception->getTraceAsString()]);
            }
        } else {
            return \response()->json(['code' => -1, 'msg' => 'file not valid, import fail']);
        }
    }

    public function handleTemplateDownload()
    {
        return response()
            ->download(realpath(base_path('public/template')) . '/dorm_meters.xlsx', '计量表导入模板.xlsx');
    }
}
